package controlmercancias.util;

import java.net.*;
import java.io.*;

public class SocketManager {

    public static final String CRLF = "\r\n";
    private Socket mySocket;
    private DataOutputStream bufferEscritura;
    private BufferedReader bufferLectura;

    public SocketManager(Socket sock) throws IOException {
        this.mySocket = sock;
        initStreams();
    }

    public SocketManager(InetAddress address, int port) throws IOException {
        mySocket = new Socket(address, port);
        initStreams();
    }

    public SocketManager(String host, int port) throws IOException {
        mySocket = new Socket(host, port);
        initStreams();
    }

    private void initStreams() throws IOException {
        bufferEscritura = new DataOutputStream(mySocket.getOutputStream());
        bufferLectura = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
    }

    public void close() throws IOException {
        closeStreams();
        closeSocket();
    }

    private void closeStreams() throws IOException {
        bufferEscritura.close();
        bufferLectura.close();
    }

    private void closeSocket() throws IOException {
        mySocket.close();
    }

    public String read() throws IOException {
        return (bufferLectura.readLine());
    }

    /**
     * Escribe el contenido y acaba con un salto de línea
     * @param contenido El contenido a escribir
     * @throws IOException 
     */
    public void write(String contenido) throws IOException {
        bufferEscritura.writeBytes(contenido + CRLF);
    }

    /**
     * Escribe n bytes del buffer. NO acaba con salto de línea
     * @param buffer El buffer del que escribir
     * @param bytes Número de bytes a escribir
     * @throws IOException 
     */
    public void write(byte[] buffer, int bytes) throws IOException {
        bufferEscritura.write(buffer, 0, bytes);
    }
}
